<template>
    <div class="page-phone">
        <van-nav-bar class="phone-title" left-arrow :fixed="true" :title="$t('m.ChangePhone')" v-if="havePhone" @click-left="goBackByHistory"></van-nav-bar>
        <van-nav-bar class="phone-title" left-arrow :fixed="true" :title="$t('m.AddPhone')" v-else @click-left="goBackByHistory"></van-nav-bar>

        <div class="login-box-inside">
            <van-button type="default" class="facebook-btn sms-add-style" :loading="btnLoading" @click="smsPhone">
                <span class="buttonText" v-if="havePhone">{{$t('m.ChangephonebySMS')}}</span>
                <span class="buttonText" v-else>{{$t('m.AddphonebySMS')}}</span>
            </van-button>
        </div>
    </div>
</template>
<script>
    import {setUserInfoPhone} from '../../static/api/mgc_api'
    import Qs from 'qs'
    export default {
        name: 'PhoneEdit',
        data() {
            return {
                havePhone: false,
                btnLoading: false,
            };
        },
        methods: {
            //facebook SMS start
            initAccountKit () {
                const tag = document.createElement('script')
                tag.setAttribute(
                    'src',
                    `https://sdk.accountkit.com/en_US/sdk.js`
                )
                tag.setAttribute('id', 'account-kit')
                tag.setAttribute('type', 'text/javascript')
                tag.onload = () => {
                    /* eslint-disable camelcase */
                    window.AccountKit_OnInteractive = this.onLoad.bind(this)
                    /* eslint-enable camelcase */
                }
                document.head.appendChild(tag)
            },
            onLoad () {
                window.AccountKit.init(
                    {
                        appId: "383669555472204",
                        // appId: "278483712850911",
                        state: '1212111',
                        version: "v1.1",
                        display: "modal",
                        fbAppEventsEnabled: true,
                    }
                )
            },
            // login callback
            loginCallback(response) {
                if (response.status === "PARTIALLY_AUTHENTICATED") {
                    var code = response.code;
                    // var csrf = response.state;
                    // Send code to server to exchange for access token
                    let data = {
                        'code': code,
                        // 'csrf': csrf
                    }
                    let params = Qs.stringify(data)
                    setUserInfoPhone(params).then((res) => {
                        if (res.data) {
                            var data = res.data
                            if (data.errorID === 0) {
                                this.editLocalUserInfo('account', data.object);
                                // this.$router.back(-1)
                                this.goBackByHistory()
                            } else {
                                this.$toast(data.message)
                                this.goBackByHistory()
                            }
                        }
                        this.btnLoading = false
                    }).catch((error) => {
                        console.log(error)
                        this.$toast('No internet, please try again')
                        this.btnLoading = false
                    })
                }
                else if (response.status === "NOT_AUTHENTICATED") {
                    console.log('Not Authenticated')
                    // this.$router.back(-1)
                    this.btnLoading = false
                }
                else if (response.status === "BAD_PARAMS") {
                    this.$toast('Bad Params')
                    // this.$router.back(-1)
                }
            },
            goBackByHistory() {
                let historyLength = localStorage.getItem('historyLength')-1 || -1
                let h_num = historyLength - window.history.length
                this.$router.go(h_num)
            },

            // phone form submission handler
            smsPhone() {
                this.btnLoading = true
                window.AccountKit.login('PHONE', {}, this.loginCallback)
            },
            //facebook SMS end
            // 修改本地缓存信息
            editLocalUserInfo(nameProperty, value) {
                let userInfo = localStorage.getItem("userInfo") || '';
                if (userInfo) {
                    userInfo = JSON.parse(userInfo);
                    userInfo[nameProperty] = value;
                    this.setNewLocalUserInfo(userInfo);
                }
            },
            // 保存用户信息
            setNewLocalUserInfo (i) {
                let _userInfo = JSON.stringify(i)
                localStorage.setItem("userInfo", _userInfo);
            },
        },
        beforeCreate() {
            if(typeof(this.$route.params.phone) == 'undefined' ){
                let historyLength = localStorage.getItem('historyLength')-1 || -1
                let h_num = historyLength - window.history.length
                this.$router.go(h_num)
            } else {
                localStorage.setItem('historyLength',window.history.length)
            }
        },
        mounted() {
            let _phone = this.$route.params.phone || ''
            if (_phone) {
                this.havePhone = true
            }
            if (!window.AccountKit) {
                this.initAccountKit()
            }
        },
        beforeRouteLeave(to, from, next) {
            if (this.btnLoading){
                // location.reload();
                next(false);
            } else {
                if (to.path != '/user/profile') {
                    next({path: '/user/profile'})
                } else {
                    next();
                }
            }
        }
    }

</script>
<style>

</style>
<style scoped>
    .login-box-inside {
        margin-top: 60px;
        padding: 12px 16px;
    }
    .facebook-btn{
        /*background-color: #3b5998;*/
        /*border:1px solid #666666;*/
        /*border:1px solid #3b5998;*/
        border:1px solid rgb(102, 102, 102);
        color:#fff;
        position: relative;
        border-radius: 5px;
        display: block;
        width: 100%;
    }
    .sms-add-style{
        margin-bottom: 15px;
    }
    span.buttonText {
        display: inline-block;
        vertical-align: middle;
        font-size: 14px;
        font-family: 'Roboto', sans-serif;
        display: block;
        padding:0 43px;
        height: 42px;
        line-height:42px;
        text-align: center;
        color:#000;
    }
</style>
